<template>
  <div class="table-gl-w">
    <a-tabs @change="changeStatus">
      <a-tab-pane v-for="tab in tabsList" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
        </template>
      </a-tab-pane>
    </a-tabs>
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" @click="submitAudit(selectIds)" v-if="searchVal.status == 1 && $authPass('procurement.supplier.quote.change.submit')">提交审核</a-button>
            <a-button type="primary" size="medium" @click="openAuditDialog(selectIds)" v-if="searchVal.status == 20 && $authPass('procurement.supplier.quote.change.audit')">审核</a-button>
            <a-button class="gray-outline" size="medium" @click="submitCancellation(selectIds)" v-if="(searchVal.status == 1 || searchVal.status == 20) && $authPass('procurement.supplier.quote.change.delete')">删除</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table class="table-two-line" ref="tableListref" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :data="tableList" size="mini" :pagination="false" :scroll="{ y: '100%' }">
            <template #columns>
              <a-table-column title="序号" :width="45">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="报价ID" :width="100">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</p>
                    <CopyText class="popup-edit-icon-hover" :val="record.billNo" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="经销商" data-index="companyName" :width="120" />
              <a-table-column title="变更类型" :width="80">
                <template #cell="{ record }">
                  <p>{{ record.changeType === 'quote' ? '变更报价' : '变更产品' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="变更方" :width="80">
                <template #cell="{ record }">
                  <p>{{ record.createType === 'company' ? '经销商' : '供应商' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="变更原因" :width="120">
                <template #cell="{ record }">
                  <TextLimit>{{ record.remark }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="createUname" title="提交人" :width="70" />
              <a-table-column title="提交时间" :width="140">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="经销商审批" :width="210" data-index="auth" key="auth">
                <template #cell="{ record }">
                  <template v-if="record.companyAuditUname">
                    <p>
                      <span>【{{ record.companyAuditUname }}】</span>
                      <span>{{ auditMap[record.companyAudit] }}，</span>
                      <span>{{ $setTime(record.gmtCompanyAudit, 'YYYY/MM/DD HH:MM') }}</span>
                    </p>
                    <TextLimit :rows="1">{{ record.companyAuditRemark }}</TextLimit>
                  </template>
                  <p v-else>--</p>
                </template>
              </a-table-column>
              <a-table-column title="供应商审批" :width="200" data-index="auth1" key="auth1">
                <template #cell="{ record }">
                  <template v-if="record.supplierAuditUname">
                    <p>
                      <span>【{{ record.supplierAuditUname }}】</span>
                      <span>{{ auditMap[record.supplierAudit] }}，</span>
                      <span>{{ $setTime(record.gmtSupplierAudit, 'YYYY/MM/DD HH:MM') }}</span>
                    </p>
                    <TextLimit :rows="1">{{ record.supplierAuditRemark }}</TextLimit>
                  </template>
                  <p v-else>--</p>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="80">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" @click="toDetail(record)">详情</a-button>
                    <a-dropdown>
                      <icon-more class="table-btn-more" />
                      <template #content>
                        <a-doption @click.stop="submitAudit([record.id])" v-if="record.status == 1 && $authPass('procurement.supplier.quote.change.submit')">提交审核</a-doption>
                        <a-doption @click.stop="openAuditDialog([record.id])" v-if="record.status == 20 && $authPass('procurement.supplier.quote.change.audit')">审核</a-doption>
                        <a-doption @click.stop="submitCancellation([record.id])" v-if="[1, 20].includes(record.status) && $authPass('procurement.supplier.quote.change.delete')">删除</a-doption>
                        <a-doption @click.stop="openLogList(record)">日志</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 报价详情 -->
  <SupChangePriceDetail v-if="showDetailDialog" :isShow="showDetailDialog" :id="currentData.id" @closed="showDetailDialog = false" />
  <!-- 审核 -->
  <SupAudit v-if="showAuditDialog" :isShow="showAuditDialog" @closed="showAuditDialog = false" @success="audit" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findSupplierQuoteChangeLogPage" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findSupplierQuoteChangePage, findDealerList, commitSupplierQuoteChange, deleteSupplierQuoteChange, auditSupplierQuoteChange } from '@/api/supplier'
  import SupChangePriceDetail from './components/supChangePriceDetail.vue'
  import SupAudit from './components/supAudit.vue'
  onMounted(async () => {
    getDealerList()
    getTableList()
  })
  const tabsList = [
    { key: 1, title: '待提交' },
    { key: 20, title: '待供应商审核' },
    { key: 10, title: '待经销商审核' },
    { key: 30, title: '已生效' },
  ]
  const auditMap = {
    '0': '未审核',
    '1': '同意',
    '-1': '驳回',
  }
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'billNo',
      label: '报价ID',
      value: ref(),
      type: 'input_search',
      width: 140,
    },
    {
      key: 'dealerId',
      label: '经销商',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'createType',
      label: '变更方',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { label: '供应商', value: 'supplier' },
        { label: '经销商', value: 'company' },
      ],
    },
    {
      key: 'changeType',
      label: '变更类型',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { label: '变更报价', value: 'quote' },
        { label: '变更产品', value: 'product' },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '变更提交时间', value: 'gmtCreate' },
        { label: '变更生效时间', value: 'gmtFinished' },
      ],
      keyWidth: '140',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: 1,
  })

  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const total = ref(0)
  const selectIds = ref([])
  const currentData = ref<any>({})
  const currentIds = ref<Array<any>>([])
  const showAuditDialog = ref(false)
  const showLogDialog = ref(false)
  const filterData = ref<any>({})
  const tableListref = ref()
  const showDetailDialog = ref(false)
  const tableListMap: any = {}

  //供应商列表
  async function getDealerList() {
    const res: any = await findDealerList()
    filterItem.value[1].optionItems = res?.data?.map((el: any) => {
      return {
        label: el.dealerName,
        value: el.id,
      }
    })
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }

  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findSupplierQuoteChangePage(params)
    tableListref.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    tableListMap.value = {}
    tableList.value.forEach((el) => {
      tableListMap.value[el.id] = el
    })
    total.value = res?.data?.total || 0
  }
  // 提交审核
  function submitAudit(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择变更单')
      return
    }
    Modal.confirm({
      title: '报价变更单提交审核',
      content: `请再次确认是否将变更单提交审核？`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await commitSupplierQuoteChange({ ids: ids })
        if (res) {
          Message.success('提交审核成功')
          getTableList()
        }
      },
    })
  }
  // 删除
  function submitCancellation(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择变更单')
      return
    }
    Modal.confirm({
      title: '删除',
      content: `请再次确认是否需要删除选中的变更单`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await deleteSupplierQuoteChange({ ids: ids })
        if (res) {
          Message.success('删除成功')
          getTableList()
        }
      },
    })
  }

  // 报价详情
  function toDetail(row: any) {
    currentData.value = row
    showDetailDialog.value = true
  }
  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }
  // 打开审核弹窗
  function openAuditDialog(ids: any) {
    if (!ids.length) {
      Message.error('请选择报价')
      return
    }
    currentIds.value = ids
    showAuditDialog.value = true
  }
  // 开始审核
  async function audit(auditRes: any) {
    const res: any = await auditSupplierQuoteChange({
      ids: currentIds.value,
      pass: auditRes.state,
      remark: auditRes.result,
    })
    if (res) {
      Message.success(auditRes.state ? '审核通过' : '已驳回')
      getTableList()
    }
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
</style>
